package com.cc.library.dao.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.cc.library.dao.CollectionDao;
import com.cc.library.domain.BorrowInfo;
import com.cc.library.domain.Collection;
import com.cc.library.domain.PageBean;

public class CollectionDaoImpl  extends HibernateDaoSupport implements CollectionDao {

	@Override
	public PageBean<Collection> getCollectionsByReader(Collection collection,int p ,int size) {


		PageBean<Collection> pb = new PageBean<Collection>();	//pageBean对象，用于分页
		//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
		pb.setPageCode(p);//设置当前页码
		pb.setPageSize(size);//设置页面记录数
		List borrowInfoList = null;
		try {
			String sql = "SELECT count(*) FROM Collection where readerId="+collection.getReader().getReaderId();
			List list = this.getSession().createQuery(sql).list();
			int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
			pb.setTotalRecord(totalRecord);	//设置总记录数
			this.getSession().close();

			//不支持limit分页
			String hql= "from Collection where reader.readerId="+collection.getReader().getReaderId();
			//分页查询
			borrowInfoList = doSplitPage(hql,p,size);
		}catch (Throwable e1) {
			e1.printStackTrace();
			throw new RuntimeException(e1.getMessage());
		}
		if(borrowInfoList!=null && borrowInfoList.size()>0){
			pb.setBeanList(borrowInfoList);
			return pb;
		}
		return null;
	}

	@Override
	public PageBean<Collection>  getCollectionsByBook(Collection collection,int p,int size) {
		PageBean<Collection> pb = new PageBean<Collection>();	//pageBean对象，用于分页
		//根据传入的pageCode当前页码和pageSize页面记录数来设置pb对象
		pb.setPageCode(p);//设置当前页码
		pb.setPageSize(size);//设置页面记录数
		List borrowInfoList = null;
		try {
			String sql = "SELECT count(*) FROM Collection where bookId="+collection.getBook().getBookId();
			List list = this.getSession().createQuery(sql).list();
			int totalRecord = Integer.parseInt(list.get(0).toString()); //得到总记录数
			pb.setTotalRecord(totalRecord);	//设置总记录数
			this.getSession().close();

			//不支持limit分页
			String hql= "from Collection where book.bookId="+collection.getBook().getBookId()+" order by createDate desc";
			//分页查询
			borrowInfoList = doSplitPage(hql,p,size);
		}catch (Throwable e1) {
			e1.printStackTrace();
			throw new RuntimeException(e1.getMessage());
		}
		if(borrowInfoList!=null && borrowInfoList.size()>0){
			pb.setBeanList(borrowInfoList);
			return pb;
		}
		return null;
	}

	@Override
	public Integer addCollection(Collection collection) {
		Integer integer = 0;
		try{
			this.getHibernateTemplate().clear();
			//save方法返回的是Serializable接口，该结果的值就是你插入到数据库后新记录的主键值
			Serializable save = this.getHibernateTemplate().save(collection);
			this.getHibernateTemplate().flush();
			integer = (Integer)save;
		}catch (Throwable e1) {
			integer = 0;
			e1.printStackTrace();
			throw new RuntimeException(e1.getMessage());
		}
		return integer;
	}



	/**
	 * 
	 * @param hql传入的hql语句
	 * @param pageCode当前页
	 * @param pageSize每页显示大小
	 * @return
	 */
	public List doSplitPage(final String hql,final int pageCode,final int pageSize){
		//调用模板的execute方法，参数是实现了HibernateCallback接口的匿名类，
		return (List) this.getHibernateTemplate().execute(new HibernateCallback(){
			//重写其doInHibernate方法返回一个object对象，
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				//创建query对象
				Query query=session.createQuery(hql);
				//返回其执行了分布方法的list
				return query.setFirstResult((pageCode-1)*pageSize).setMaxResults(pageSize).list();

			}

		});

	}

	@Override
	public boolean deleteCollection(Collection collection) {
		try {
			this.getHibernateTemplate().delete(collection);
			return  true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	@Override
	public Collection findCollectionById(int collectionId) {
		// TODO Auto-generated method stub
		return (Collection)getHibernateTemplate().get(Collection.class, collectionId);
	}

	@Override
	public Collection findCollectionByBookAndReader(Collection collection) {
		//不支持limit分页
		String hql= "from Collection where book=? and reader=?";
		List cs = getHibernateTemplate().find(hql,new Object[]{collection.getBook(),collection.getReader()});
		if(cs.size()>0){
			return (Collection) cs.get(0);
		}else{
			return null;
		}
	}


}
